package com.qd.qx.ui.main.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.qd.chatui.adapter.ChatAdapter;
import com.qd.chatui.adapter.CommonFragmentPagerAdapter;
import com.qd.chatui.enity.FullImageInfo;
import com.qd.chatui.enity.MessageInfo;
import com.qd.chatui.ui.activity.FullImageActivity;
import com.qd.chatui.ui.fragment.ChatEmotionFragment;
import com.qd.chatui.ui.fragment.ChatFunctionFragment;
import com.qd.chatui.ui.fragment.ChatMyFunctionFragment;
import com.qd.chatui.util.Constants;
import com.qd.chatui.util.GlobalOnItemClickManagerUtils;
import com.qd.chatui.util.MediaManager;
import com.qd.chatui.util.MyUtils;
import com.qd.chatui.widget.EmotionInputDetector;
import com.qd.chatui.widget.NoScrollViewPager;
import com.qd.chatui.widget.StateButton;
import com.qd.common.base.BaseActivity;
import com.qd.common.baserx.RxBus;
import com.qd.common.baserx.RxSubscriber;
import com.qd.common.commonutils.ImageLoaderUtils;
import com.qd.common.commonutils.JsonUtils;
import com.qd.common.commonutils.ToastUitl;
import com.qd.qx.R;
import com.qd.qx.api.Api;
import com.qd.qx.api.ApiServerConstants;
import com.qd.qx.api.MyXMPPTCPConnection;
import com.qd.qx.bean.MembersBean;
import com.qd.qx.bean.MessageInfoBean;
import com.qd.qx.bean.MsgStateBean;
import com.qd.qx.bean.PeopleBean;
import com.qd.qx.bean.UserData;
import com.qd.qx.db.DbHelper;
import com.qd.qx.db.bean.MsgList;
import com.qd.qx.db.bean.People;
import com.qd.qx.db.bean.User;
import com.qd.qx.im.ChatInfoUtils;
import com.qd.qx.im.ImRxBus;
import com.qd.qx.ui.module1.ChatMoreActivity;
import com.qd.qx.ui.module4.MeInfoActivity;

import org.greenrobot.eventbus.EventBus;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.MultiUserChatManager;
import org.jivesoftware.smackx.vcardtemp.packet.VCard;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Code is far away from bug with the animal protecting
 * Author：YS on 2018/10/15
 * Function：聊天界面
 */
public class ChatActivity extends BaseActivity {

    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.ivMore)
    ImageView ivMore;

    @BindView(R.id.chatRcv)
    EasyRecyclerView chatList;
    @BindView(R.id.emotion_voice)
    ImageView emotionVoice;
    @BindView(R.id.edit_text)
    EditText editText;
    @BindView(R.id.voice_text)
    TextView voiceText;
    @BindView(R.id.emotion_button)
    ImageView emotionButton;
    @BindView(R.id.emotion_add)
    ImageView emotionAdd;
    @BindView(R.id.emotion_send)
    StateButton emotionSend;
    @BindView(R.id.viewpager)
    NoScrollViewPager viewpager;
    @BindView(R.id.emotion_layout)
    RelativeLayout emotionLayout;
    private ChatAdapter chatAdapter;
    private LinearLayoutManager layoutManager;
    private int msg_list_id;
    private String to_name;
    private String realName;//名字
    private DbHelper helper;
    private List<MessageInfo> msgList = new ArrayList<>();
    private User user;
    private Subscription subscription;
    private XMPPTCPConnection xmpptcpConnection;

    //chatui 组件
    private EmotionInputDetector mDetector;
    private ArrayList<Fragment> fragments;
    private ChatEmotionFragment chatEmotionFragment;
    private ChatMyFunctionFragment chatFunctionFragment;
    private CommonFragmentPagerAdapter chatUIadapter;
    //录音相关
    int animationRes = 0;
    int res = 0;
    AnimationDrawable animationDrawable = null;
    private ImageView animView;
    private int page = -1;//分页加载

    private boolean isSingeChat = true;//是否为单聊
    private String roomName = "";//群聊时 群的名字
    String sendTips = "";//提示消息通知

    /**
     * 入口
     *
     * @param activity
     */
    public static void startAction(Activity activity, int msg_list_id, String to_name, String realName) {
        Intent intent = new Intent(activity, ChatActivity.class);
        intent.putExtra("msg_list_id", msg_list_id);
        intent.putExtra("to_name", to_name);
        intent.putExtra("realName", realName);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.fade_in,
                com.qd.common.R.anim.fade_out);
    }

    /**
     * 入口
     *
     * @param activity
     */
    public static void startAction(Activity activity, int msg_list_id, String to_name, String realName, String sendTips) {
        Intent intent = new Intent(activity, ChatActivity.class);
        intent.putExtra("msg_list_id", msg_list_id);
        intent.putExtra("to_name", to_name);
        intent.putExtra("realName", realName);
        intent.putExtra("sendTips", sendTips);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.fade_in,
                com.qd.common.R.anim.fade_out);
    }

    /**
     * 根据名字寻找数据库的列表id
     *
     * @param to_name
     * @return
     */
    private int msgListId(String to_name) {
        MsgList msgListBean = helper.getMsgList(user.getUser_id(), to_name);
        if (null == msgListBean) {
            return -1;
        }
        return msgListBean.getMsg_list_id();
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_chat;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        user = MyXMPPTCPConnection.getInstance().GetUser();
        helper = MyXMPPTCPConnection.getInstance().getDbHelper();
        new Thread() {
            @Override
            public void run() {
                super.run();
                xmpptcpConnection = MyXMPPTCPConnection.getInstance().getConnection();
            }
        }.start();

        msg_list_id = getIntent().getIntExtra("msg_list_id", -1);
        to_name = getIntent().getStringExtra("to_name");
        realName = getIntent().getStringExtra("realName");
        sendTips = getIntent().getStringExtra("sendTips");
        MyXMPPTCPConnection.OnlineChatName = to_name;
        if (-1 == msg_list_id) {
            msg_list_id = msgListId(to_name);
        }
        ivMore.setBackgroundResource(R.drawable.gengduo);
        tvTitle.setText(realName);
        if (to_name.contains("conference")) {
            isSingeChat = false;//群聊
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    roomName = MyXMPPTCPConnection.getInstance().getGroupNickName(to_name);
                    //sendTips 不为空那么先发一条 提示消息
                    if (!TextUtils.isEmpty(sendTips)) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                sendTips(sendTips);
                            }
                        });
                    }
                }
            }.start();

        } else {
            isSingeChat = true;//单聊
        }
        initWidget();
        newMsg();
        getMsg();
        markUnreadCount();


        RxBus.getInstance().register("chatSendTips").subscribe(new Action1() {
            @Override
            public void call(Object o) {
                String tips = (String) o;
                // 不为空发一条 邀请提示消息
                if (!TextUtils.isEmpty(tips)) {
                    sendTips(tips);
                }
            }
        });

    }

    /**
     * 发送一条 通知消息
     *
     * @param tips
     */
    private void sendTips(String tips) {
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setContent(tips);
        messageInfo.setMsgType(EmotionInputDetector.sendType_Tips);
        sendMsgAction(Constants.CHAT_ITEM_TYPE_TIPS, messageInfo);
    }

    @Override
    protected void onResume() {
        getMsg();
        super.onResume();
    }

    /**
     * 重置该会话的全部未读
     */
    public void markUnreadCount() {
        helper.markUnreadCount(user.getUser_id(), msg_list_id);
    }

    private void initWidget() {
        fragments = new ArrayList<>();
        chatEmotionFragment = new ChatEmotionFragment();
        fragments.add(chatEmotionFragment);
        chatFunctionFragment = new ChatMyFunctionFragment(chatUiClickCallBack);
        fragments.add(chatFunctionFragment);
        chatUIadapter = new CommonFragmentPagerAdapter(getSupportFragmentManager(), fragments);
        viewpager.setAdapter(chatUIadapter);
        viewpager.setCurrentItem(0);

        mDetector = EmotionInputDetector.with(this)
                .setEmotionView(emotionLayout)
                .setViewPager(viewpager)
                .bindToContent(chatList)
                .bindToEditText(editText)
                .bindToEmotionButton(emotionButton)
                .bindToAddButton(emotionAdd)
                .bindToSendButton(emotionSend)
                .bindToVoiceButton(emotionVoice)
                .bindToVoiceText(voiceText)
                .build().setChatUiClickCallBack(chatUiClickCallBack);

        GlobalOnItemClickManagerUtils globalOnItemClickListener = GlobalOnItemClickManagerUtils.getInstance(this);
        globalOnItemClickListener.attachToEditText(editText);

        chatAdapter = new com.qd.chatui.adapter.ChatAdapter(this, !isSingeChat);
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        chatList.setLayoutManager(layoutManager);
        chatList.setAdapter(chatAdapter);
        chatList.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        chatAdapter.handler.removeCallbacksAndMessages(null);
                        chatAdapter.notifyDataSetChanged();
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        chatAdapter.handler.removeCallbacksAndMessages(null);
                        mDetector.hideEmotionLayout(false);
                        mDetector.hideSoftInput();
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        chatAdapter.addItemClickListener(itemClickListener);
    }

    /**
     * chatui 输入框的回调
     */
    EmotionInputDetector.ChatUiClickCallBack chatUiClickCallBack = new EmotionInputDetector.ChatUiClickCallBack() {
        @Override
        public void clickCallBack(final MessageInfo messageInfo) {
            sendMsgAction(Constants.CHAT_ITEM_TYPE_RIGHT, messageInfo);
        }
    };

    private void sendMsgAction(int sendType, final MessageInfo messageInfo) {
        messageInfo.setType(sendType);
        messageInfo.setSendState(Constants.CHAT_ITEM_SENDING);
        messageInfo.setHeader(UserData.getInstance().getHeaderImg());
        messageInfo.setSendTime(System.currentTimeMillis() + "");
        messageInfo.setMsgChatId(MyXMPPTCPConnection.getInstance().newMsgChatId(user.getLogin_name()));
        messageInfo.setRealName(UserData.getInstance().getRealName());
        //TODO 发送消息第一步 本地发送 sending状态
        sendMsgFirst(messageInfo);
        switch (messageInfo.getMsgType()) {
            case EmotionInputDetector.sendType_Img:
                ChatInfoUtils.getInstance().uploadFile(messageInfo, to_name, "0", new ChatInfoUtils.ChatInfoCallBack() {
                    @Override
                    public void callBack(Object object) {
                        MessageInfo messageInfo = (MessageInfo) object;
                        if (Constants.CHAT_ITEM_SEND_SUCCESS == messageInfo.getSendState()) {
                            //上传成功 在通过im发送
                            sendMsgSecond(messageInfo);
                        } else {
                            ToastUitl.showShort("发送失败");
                            setMsgState(messageInfo, Constants.CHAT_ITEM_SEND_ERROR);
                        }

                    }
                });
                //图片
                break;
            case EmotionInputDetector.sendType_File:
                //文件
                break;
            case EmotionInputDetector.sendType_Audio:
                //音频
                break;
            case EmotionInputDetector.sendType_Video:
                //视频
                break;
            case EmotionInputDetector.sendType_Text:
                //默认发文字
                sendMsgSecond(messageInfo);
                break;
        }

    }


    /**
     * 发送消息第一步 发出本地消息 然后调用第二步通过im 发送 然后更新状态
     *
     * @param messageInfo
     */
    private void sendMsgFirst(MessageInfo messageInfo) {
        helper.insertOneMsg(user.getUser_id(), to_name, messageInfo.getMsgChatId(), messageInfo.getContent(),
                messageInfo.getSendTime(), user.getUser_name(),
                messageInfo.getType(),
                messageInfo.getMsgType(), messageInfo.getSendState(), messageInfo.getHeader(),
                false, realName, user.getReal_name(), roomName);
        msgList.add(messageInfo);
        setTimeStampTag();
        chatAdapter.add(messageInfo);
        chatList.scrollToPosition(chatAdapter.getCount() - 1);
        chatAdapter.notifyDataSetChanged();
    }

    /**
     * 发送消息第二步 通过im api发送消息
     *
     * @param messageInfo
     */
    private void sendMsgSecond(MessageInfo messageInfo) {
        boolean b = sendMsg(messageInfo, to_name);
        if (b) {
            setMsgState(messageInfo, Constants.CHAT_ITEM_SEND_SUCCESS);
        } else {
            setMsgState(messageInfo, Constants.CHAT_ITEM_SEND_ERROR);
        }
    }

    /**
     * 设置单条消息状态并刷新list
     *
     * @param messageInfo
     * @param state
     */
    private void setMsgState(MessageInfo messageInfo, int state) {
//        msgList.add(messageInfo);
//        setTimeStampTag();
//        chatAdapter.add(messageInfo);
        // messageInfo.setSendState(state);// Constants.CHAT_ITEM_SEND_ERROR
        //chatList.scrollToPosition(chatAdapter.getCount() - 1);
        helper.updateMsgState(messageInfo.getMsgChatId(), state);
        getMsg();
    }

    /**
     * item点击事件
     */
    private ChatAdapter.onItemClickListener itemClickListener = new ChatAdapter.onItemClickListener() {
        @Override
        public void onHeaderClick(int position) {
            ToastUitl.showShort("onHeaderClick");
        }

        @Override
        public void onImageClick(View view, int position) {
            int location[] = new int[2];
            view.getLocationOnScreen(location);
            FullImageInfo fullImageInfo = new FullImageInfo();
            fullImageInfo.setLocationX(location[0]);
            fullImageInfo.setLocationY(location[1]);
            fullImageInfo.setWidth(view.getWidth());
            fullImageInfo.setHeight(view.getHeight());
            fullImageInfo.setImageUrl(msgList.get(position).getContent());
            EventBus.getDefault().postSticky(fullImageInfo);
            startActivity(new Intent(ChatActivity.this, FullImageActivity.class));
            overridePendingTransition(0, 0);
            // PhotosDetailActivity.startAction(ChatActivity.this,msgList.get(position).getImageUrl());
        }

        @Override
        public void onVoiceClick(final ImageView imageView, final int position) {
            if (animView != null) {
                animView.setImageResource(res);
                animView = null;
            }
            switch (msgList.get(position).getType()) {
                case Constants.CHAT_ITEM_TYPE_LEFT:
                    animationRes = com.qd.chatui.R.drawable.voice_left;
                    res = com.qd.chatui.R.mipmap.icon_voice_left3;
                    break;
                case Constants.CHAT_ITEM_TYPE_RIGHT:
                    animationRes = com.qd.chatui.R.drawable.voice_right;
                    res = com.qd.chatui.R.mipmap.icon_voice_right3;
                    break;
            }
            animView = imageView;
            animView.setImageResource(animationRes);
            animationDrawable = (AnimationDrawable) imageView.getDrawable();
            animationDrawable.start();
            MediaManager.playSound(msgList.get(position).getContent(), new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    animView.setImageResource(res);
                }
            });
        }
    };

    /**
     * 观察新消息
     */
    public void newMsg() {
        subscription = ImRxBus.getInstance().toObserverable(Message.class).
                observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Message>() {
                    @Override
                    public void call(Message message) {
                        if (message.getFrom().equals(to_name)) {
                            getMsg();
                        }
                    }
                });
    }

    /**
     * 重数据库中获取聊天记录
     */
    public void getMsg() {
        try {
            //如果回话列表id为-1 那么先从库中查取
            if (-1 == msg_list_id) {
                msg_list_id = msgListId(to_name);
            }
            msgList.clear();
            chatAdapter.clear();
            msgList.addAll(helper.getAllMsg(msg_list_id, page));
            setMsgListHeaderImg();
            setTimeStampTag();
            chatAdapter.addAll(msgList);
            chatAdapter.notifyDataSetChanged();
            chatList.scrollToPosition(msgList.size() - 1);
            MsgList msgbean = helper.getMsgList(user.getUser_id(), to_name);
            if (null != msgbean) {
                tvTitle.setText(msgbean.getRealName());
            }
            markUnreadCount();
        } catch (Exception e) {
            e.printStackTrace();
            ToastUitl.showShort(e.toString());
        }
    }

    /**
     * 设置聊天列表头像
     */
    private void setMsgListHeaderImg() {
        for (final MessageInfo info : msgList) {
            //getfromname  这个是消息发送人的 name+@+ip
            ChatInfoUtils.getInstance().getUserInfo(info.getFromName(), new ChatInfoUtils.ChatInfoCallBack() {
                @Override
                public void callBack(Object object) {
                    if (null != object) {
                        List<PeopleBean> list = (List<PeopleBean>) object;
                        if (null != list && list.size() != 0) {
                            info.setHeader(list.get(0).getHeaderImg());
                            chatAdapter.notifyDataSetChanged();
                        }
                    }
                }
            });
        }

    }


    /**
     * 重置当前消息集合 设置时间戳显示逻辑
     */
    private void setTimeStampTag() {
        if (null == msgList || msgList.size() == 0) {
            return;
        }
        String lastShowTimeStamp = "";
        for (MessageInfo messageInfo : msgList) {
            if (messageInfo.getSendTime().length() < 13) {
                messageInfo.setSendTime(messageInfo.getSendTime() + "000");
            }
            if (TextUtils.isEmpty(lastShowTimeStamp)) {
                lastShowTimeStamp = messageInfo.getSendTime();
                messageInfo.setShowTimeStamp(true);
            }
            //大于五分钟
            if ((Long.parseLong(messageInfo.getSendTime()) - Long.parseLong(lastShowTimeStamp)) > 300000) {
                lastShowTimeStamp = messageInfo.getSendTime();
                messageInfo.setShowTimeStamp(true);
            }
        }

    }


    /**
     * 发送一条消息
     *
     * @param to_name 好友userJid
     * @return
     */
    public boolean sendMsg(MessageInfo messageInfo, String to_name) {
        Message msg = messageInfoToMessage(messageInfo);
        boolean isSend;
        try {
            ChatManager manager = ChatManager.getInstanceFor(xmpptcpConnection);
            //得到与另一个帐号的连接，这里是一对  单聊
            //格式为azhon@106.14.20.176;服务器ip
            //名字 @  域名  /  mobile
            //serviceNames->conference.106.14.20.176   群聊toname
            if (isSingeChat) {
                //单聊
                Chat chat = manager.createChat(to_name + "/" + ApiServerConstants.XMPP_RESOURCE, null);
                chat.sendMessage(msg);
            } else {
                //群聊
                MultiUserChat multiUserChat = MultiUserChatManager.getInstanceFor(xmpptcpConnection).getMultiUserChat(to_name);
                multiUserChat.sendMessage(msg);
            }
//
//            helper.insertOneMsg(user.getUser_id(), to_name, messageInfo.getMsgChatId(), messageInfo.getContent(),
//                    messageInfo.getSendTime(), user.getUser_name(),
//                    messageInfo.getType(),
//                    messageInfo.getMsgType(), messageInfo.getSendState(), messageInfo.getHeader(),
//                    false, realName, user.getReal_name(), roomName);
            isSend = true;
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
            ToastUitl.showShort("发送失败： " + e.toString());
            isSend = false;
        }
        return isSend;
    }

    /**
     * 本地bean转消息体
     *
     * @param messageInfo
     * @return
     */
    private Message messageInfoToMessage(MessageInfo messageInfo) {
        Message message = new Message();
        message.setBody(messageInfo.getContent());
        message.addBody("sendTime", messageInfo.getSendTime());
        message.addBody("msgType", messageInfo.getMsgType());
        message.addBody("realName", messageInfo.getRealName());
        //  message.addBody("header", messageInfo.getHeader());
        message.addBody("msgChatId", messageInfo.getMsgChatId());
        message.addBody("roomName", roomName);// 单聊为空  群聊为群的名字
        message.addBody("sendFrom", UserData.getInstance().getChatName());
        message.setStanzaId(System.currentTimeMillis() + "");//设置消息id
        return message;
    }

    @Override
    protected void onDestroy() {
        if (!subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
        MyXMPPTCPConnection.OnlineChatName = "";
        RxBus.getInstance().unregister("chatSendTips");
        super.onDestroy();
    }


    @OnClick({R.id.ivBack, R.id.ivMore})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.ivMore:
                ChatMoreActivity.startAction(ChatActivity.this, to_name);
                break;
        }
    }


}
